package models

import (
	"errors"
	"gorm.io/gorm"
	"project/jwt-prac/db"
	"time"
)

type User struct {
	gorm.Model
	Username     string    `gorm:"column:username;unique;not null;"`
	Email        string    `gorm:"column:email;unique;not null"`
	PasswordHash string    `grom:"column:passwordhash"`
	LoginIp      string    `grom:"column:login_ip;not null"`
	LoginTime    time.Time `grom:"column:login_time;not null"`
}

//向数据库中插入一条用户数据
func CreateUserDB(u *User) (int, error) {
	err := db.DB.Create(u).Error
	if err != nil {
		return 500, errors.New("internal server error")
	}
	return 200, nil
}

func UpdateUserDB(uniqueKey interface{}, u User) (int, error) {
	//跟新user信息，会忽略零值字段
	err := db.DB.Model(User{}).Where("username = ?", uniqueKey).Updates(u).Error
	if err != nil {
		return 500, err
	}
	return 200, err
}
